﻿
using System;
using System.Drawing;

using GECS.Util;

namespace GECS.GraphicsUtil {

    /// <summary>
    /// Represents a game font made from a single sprite sheet. Uses images to
    /// represent alphabets. You can use the GFontAdvanced class to load the fonts
    /// from the font descriptors like this.
    /// <code>
    /// GFont font = GFontAdvanced.GetFont(Game.LoadImage(&quot;&lt;path-to-image&gt;&quot;), &quot;&lt;path-to-descriptor&gt;&quot;);
    /// </code>
    /// </summary>
    public class GFont {

        private Image[] imgs;

        private char[] characters;

        /// <summary>
        /// Constructs a GFont object with a main image, numRows, numColumns and the
        /// order of alphabets in the image.
        /// </summary>
        /// <param name="img">The main image.</param>
        /// <param name="rows">The number of rows.</param>
        /// <param name="cols">The number of columns.</param>
        /// <param name="order">The order of the alphabets in the image.</param>
        /// <seealso cref="GECS.Util.ImageTool"></seealso>
        public GFont(Image img, int rows, int cols, char[] order) {
            imgs = ImageTool.SplitImage(img, rows, cols);
            characters = order;
        }

        /// <summary>
        /// Constructs a GFont object with a main image, numRows, numColumns and the
        /// order of alphabets in the image.
        /// </summary>
        /// <param name="img">The main image.</param>
        /// <param name="rows">The number of rows.</param>
        /// <param name="cols">The number of columns.</param>
        /// <param name="order">The order of the alphabets in the image.</param>
        /// <seealso cref="GECS.Util.ImageTool"></seealso>
        public GFont(Image img, int rows, int cols, string order)
        : this(img, rows, cols, order.ToCharArray()) {}

        /// <summary>
        /// This is the method which we use to draw text on the window. Note that the
        /// maximum length of the string is 40 cols.
        /// </summary>
        /// <param name="txt">The text to be drawn.</param>
        /// <param name="g">The graphics context.</param>
        /// <param name="x">The starting x-position.</param>
        /// <param name="y">The starting y-position.</param>
        public void RenderText(string txt, Graphics g, int x, int y) {
            int x_pos = x;
            int y_pos = y;
            for (int i=0; i<txt.Length; i++) {
                if (txt[i] != ' ') {
                    for (int j=0; j<characters.Length; j++) {
                        if (txt[i] == characters[j]) {
                            g.DrawImage(imgs[j], x_pos, y_pos);
                            x_pos += imgs[0].Width;
                        }
                    }
                } else if (txt[i] == '\n') {
                    y_pos += imgs[0].Height;
                } else {
                    x_pos += imgs[0].Width;
                }
            }
        }

    }

}
